//
//  NiubiContentView.m
//  danpin
//
//  Created by chuangjia on 16/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "NiubiContentView.h"
#import "viewconfig.h"
#import "NiubiModel.h"
#import "NiubiStyleCell_subject.h"
#import "NiubiStyleCell_baoliao.h"
#import "NiubiStyleCell_banner.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "YiRefreshHeader.h"
@interface NiubiContentView ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbview;
@property(nonatomic,strong)NSMutableArray *itemDatas;
@property(nonatomic,strong)NSString *currentPage;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,strong)YiRefreshHeader *refreshHeader;
@property(nonatomic,assign) float lastOffsetY;
//
@property(nonatomic,assign)BOOL isUseControl;
@end

@implementation NiubiContentView
@synthesize tbview=_tbview;
@synthesize itemDatas=_itemDatas;
@synthesize currentPage=_currentPage;
@synthesize refreshHeader=_refreshHeader;
@synthesize actionstring=_actionstring;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _lastOffsetY= 0;
        _isUseControl = NO;
        _currentPage= @"1";
        if (!_itemDatas) {
            _itemDatas =[[NSMutableArray alloc] init];
        }
        [self initUI];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(scrollToTop)
                                                     name:@"scrollToTop"
                                                   object:nil];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NiubiModel cancelRequest];
    self.tbview =nil;
    self.itemDatas =nil;
    self.refreshHeader = nil;
    NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)layoutSubviews
{
    [super layoutSubviews];
}
-(void)reloadData
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    self.isRequesting = YES;
    self.isRefresh = YES;
    self.isLoadFinished = NO;
    self.isUseControl = NO;
    self.currentPage= @"1";
    [NiubiModel cancelRequest];
    if (self.itemDatas.count==0) {
        [self getbaoliaodatawithaction:self.actionstring isCache:YES];
    }else{
        [self getbaoliaodatawithaction:self.actionstring isCache:NO];
    }
}
-(void)scrollToTop
{
    if(_tbview)
    {
        [_tbview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }
}
-(void)setCallBack:(void(^)(UIView*,id,id,id))callback
{
    self.actionBlock =callback;
}
-(void)initUI
{
    if (_tbview) {
        _tbview.dataSource=nil;
        _tbview.delegate =nil;
        [_tbview removeFromSuperview];
        _tbview=nil;
    }
    _tbview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) style:UITableViewStyleGrouped];
    _tbview.delegate = self;
    _tbview.dataSource = self;
    _tbview.backgroundColor =[UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1];
    _tbview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbview.showsHorizontalScrollIndicator = NO;
    _tbview.showsVerticalScrollIndicator = NO;
    _tbview.scrollsToTop = NO;
    [self addSubview:_tbview];
    
    __weak typeof (self) wSelf = self;
    // YiRefreshHeader  头部刷新按钮的使用
    _refreshHeader=[[YiRefreshHeader alloc] init];
    _refreshHeader.scrollView=_tbview;
    [_refreshHeader header];
    
    _refreshHeader.beginRefreshingBlock=^(){
        if (wSelf.isRefresh) {
            return ;
        }
        wSelf.isRequesting = YES;
        wSelf.isRefresh = YES;
        wSelf.isLoadFinished = NO;
        wSelf.isUseControl = YES;
        wSelf.currentPage= @"1";
//        [wSelf.tbview setShowsInfiniteScrolling:YES];
        if (wSelf.itemDatas.count==0) {
             [wSelf getbaoliaodatawithaction:wSelf.actionstring isCache:YES];
        }else{
            [wSelf getbaoliaodatawithaction:wSelf.actionstring isCache:NO];
        }
       
    };
    [_tbview addInfiniteScrollingWithActionHandler:^{
        
        if (wSelf.isRequesting) {
            return;
        }
        if (wSelf.isLoadFinished) {
            if (wSelf.isRefresh) {
                wSelf.isRefresh = NO;
                [wSelf.refreshHeader endRefreshing];
            }
            //停止菊花
            [wSelf.tbview.infiniteScrollingView stopAnimating];
            [wSelf.tbview setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbview.infiniteScrollingView startAnimating];
        if([wSelf.itemDatas count]==0)
        {
            return;
        }
        [wSelf  getbaoliaodatawithaction:wSelf.actionstring isCache:NO];
    }];

}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.itemDatas.count;
   
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return PHOTO_TIME_PADDING;
    }
    return PHOTO_TIME_PADDING/2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return PHOTO_TIME_PADDING/2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.section >= _itemDatas.count)
    {
        return 0.01;
    }
    NSDictionary *dict = [_itemDatas objectAtIndex:indexPath.section];
   
    NSString * strType = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"item_type"]] replaceNullString];
    
    int item_type = [strType intValue] ;//[[dict objectForKey:@"item_type"] intValue];
    if(item_type == 1)
    {
        return [NiubiStyleCell_banner returnCellHeight:nil];
    }
    else if(item_type == 2)
    {
        return [NiubiStyleCell_subject returnCellHeight:nil];
    }
    else if(item_type == 3)
    {
        NSDictionary *data =[dict objectForKey:@"data"];
        return [NiubiStyleCell_baoliao returnCellHeight:data];
        
    }
    return 0.01;
    
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section >= _itemDatas.count)
    {
        //如果前端输出了客户端无法理解的type，客户端显示一个白色的cell
        return [self getErrorcell:tableView];
    }
    
    NSDictionary *dict = [_itemDatas objectAtIndex:indexPath.section];
    NSString * strType = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"item_type"]] replaceNullString];
    
    int item_type = [strType intValue];
    if(item_type == 1)
    {

        NiubiStyleCell_banner *cell = (NiubiStyleCell_banner*)[tableView dequeueReusableCellWithIdentifier:@"NiubiStyleCell_banner"];
        if(cell == nil)
        {
            cell = [[NiubiStyleCell_banner alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NiubiStyleCell_banner"];
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath)
             {
                 [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
             }];
        }
        [cell showInfo:dict key:@"NiubiStyleCell_banner" indexPath:indexPath];
        
        return cell;
        
    }
    else if(item_type == 2)
    {
  
        NiubiStyleCell_subject *cell = (NiubiStyleCell_subject*)[tableView dequeueReusableCellWithIdentifier:@"NiubiStyleCell_subject"];
        if(cell == nil)
        {
            cell = [[NiubiStyleCell_subject alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NiubiStyleCell_subject"];
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath)
             {
                 [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
             }];
        }
        [cell showInfo:dict key:@"NiubiStyleCell_subject" indexPath:indexPath];
    
        return cell;
    }else if(item_type == 3)
    {

        NiubiStyleCell_baoliao *cell = (NiubiStyleCell_baoliao*)[tableView dequeueReusableCellWithIdentifier:@"NiubiStyleCell_baoliao"];
        if(cell == nil)
        {
            cell = [[NiubiStyleCell_baoliao alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NiubiStyleCell_baoliao"];
        }
        NSDictionary *data =[dict objectForKey:@"data"];
        [cell showInfo:data indexPath:indexPath];
        return cell;
    }
    else
    {
        //如果前端输出了客户端无法理解的type，客户端显示一个白色的cell
        return [self getErrorcell:tableView];
    }
}

- (UITableViewCell*)getErrorcell:(UITableView*)tableView
{
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ErrorEmptyCell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ErrorEmptyCell"];
    }
    return  cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section>=[_itemDatas count]) {
        return;
    }
    NSDictionary *dict =[_itemDatas objectAtIndex:indexPath.section];
    NSString * strType = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"item_type"]] replaceNullString];
    int item_type = [strType intValue]; 
    if (item_type==3)
    {
        NSDictionary *data =[dict objectForKey:@"data"];
        if (self.actionBlock)
        {
            self.actionBlock(self,data,nil,indexPath);
        }
    }
  
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_banner:
        {
            if (self.actionBlock)
            {
                self.actionBlock(self,obj,key,indexPath);
            }
            
        }
            break;
        case BEventType_Topic:
        {
            if (self.actionBlock)
            {
                self.actionBlock(self,obj,key,indexPath);
            }
            
        }
        default:
            break;
    }
}
-(void)stopAnimation
{
    if (self.isRefresh) {
        self.isRefresh = NO;
        [self.refreshHeader endRefreshing];
    }
    if (self.isRequesting) {
        self.isRequesting = NO;
        [self.tbview.infiniteScrollingView stopAnimating];
    }
    
}
-(void)getbaoliaodatawithaction:(NSString*)actionstring isCache:(BOOL)isCache
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:self.currentPage forKey:@"page"];
    [dict setValue:actionstring forKey:@"dpzone"];
    
    self.isRequesting = YES;
     __weak typeof (self) wSelf = self;
    [NiubiModel baoliaoListWithParams:dict loadCache:isCache Block:^(NSArray *itemarray, NSInteger page, NSError *error)
    {
        if (page<=2 && (itemarray && itemarray.count>0))
        {
            [wSelf.itemDatas removeAllObjects];
        }
        [wSelf.tbview.infiniteScrollingView stopAnimating];
        //关闭刷新
        if (wSelf.isRefresh) {
            wSelf.isRefresh = NO;
            [wSelf.refreshHeader endRefreshing];
        }
        wSelf.isRequesting = NO;
        if (page==-1) {
            return;
        }
        wSelf.currentPage =[NSString stringWithFormat:@"%ld",(long)page];
        [wSelf parwithArray:itemarray page:page];
        
    }];
}
-(void)parwithArray:(NSArray *)ar page:(NSInteger)page
{
    if(ar ==nil || ar.count==0)
    {
        self.isRequesting = NO;
        if ( page>=1 )
        {
           // [self.tbview reloadData];
            
            self.tbview.tableFooterView =[ZShare footerView:@""];
            
            //请求了所有数据
            [self.tbview.infiniteScrollingView stopAnimating];
            [self.tbview setShowsInfiniteScrolling:NO];
            
        }
        return;
    }
   
    //以下代码为了解决用户翻页中间，有新的内容更新，造成两页之间有相同的商品信息
    for( int i = 0; i < [ar count]; i++)
    {
        NSDictionary *dict =[ar objectAtIndex:i];
        NSString * strType = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"item_type"]] replaceNullString];
        
        int item_type = [strType intValue];//[[dict objectForKey:@"item_type"] intValue];
        
        if (item_type==3)
        {
            NSDictionary* dcBaoliao = (NSDictionary*)[dict objectForKey:@"data"];
            
            if(dcBaoliao == nil)
                continue;
            
            if([dcBaoliao isKindOfClass:[NSDictionary class]] == NO)
                continue;
            
            NSNumber * ID = [dcBaoliao objectForKey:@"id"];
            
            if(ID == nil)
                continue;
            
            if([ID isKindOfClass:[NSNumber class]] == NO)
                continue;
            
            
            long nCount = [self.itemDatas count];
            
            BOOL isRepeated = NO;
            for(long n = nCount  - 1; n > 0 &&  n > (nCount - 10); n--)
            {
                //倒叙查找最近的10个items，检查id是否重复。 如果重复就不添加到数组。
                NSDictionary *dictt =[self.itemDatas objectAtIndex:n];
                
                NSDictionary* oldBaoliao = [dictt objectForKey:@"data"];
                if(oldBaoliao == nil)
                    continue;
                
                if([oldBaoliao isKindOfClass:[NSDictionary class] ]== NO)
                    continue;
                
                NSNumber * oldID = [oldBaoliao objectForKey:@"id"];
                if(oldID && [oldID isKindOfClass:[NSNumber class]] && [oldID isEqualToValue:ID])
                {
                    isRepeated = YES;
                    break;
                }
            }
            
            if(isRepeated == NO)
            {
                [self.itemDatas addObject:dict];
            }
        }else{
            [self.itemDatas addObject:dict];
        }
    }
  
    [self.tbview reloadData];
    
    if ( self.isUseControl) {
        //关闭刷新
        if (self.isRefresh) {
            self.isRefresh = NO;
            [self.refreshHeader endRefreshing];
        }
        self.isRequesting = NO;
    }

}

-(UIView *)footerView:(NSString*)msg
{
    if (msg==nil || msg.length==0) {
        msg=[ZShare sharedInstance].refreshFooter;
    }
    UIView *footerview =[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150)];
    footerview.backgroundColor=[UIColor clearColor];
    UILabel *footLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 65, [UIScreen mainScreen].bounds.size.width, 20)];
    footLabel.backgroundColor = [UIColor clearColor];
    footLabel.textColor = UIColorFromRGB(0xcccccc);
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.font = FONT(14);
    footLabel.text =msg;
    [footerview addSubview:footLabel];
    return footerview;
}


-(void) enableScrollsToTop:(BOOL)enable
{
    _tbview.scrollsToTop = enable;
}


- (BOOL) scrollViewShouldScrollToTop:(UIScrollView*) scrollView
{
   // if (scrollView == self.myTableView) {          return YES;      } else {          return NO;      }
    return YES;
}

@end
